<script>
  import { createEventDispatcher } from "svelte";

  export let images = [];
  export let visible = false;
  export let currentIndex = 0;

  const dispatch = createEventDispatcher();

  let showFullscreen = false;
  let fullscreenIndex = 0;
  let scale = 1;
  let scaleInput = "100";
  let showThumbnails = false;
  let isDragging = false;
  let dragStart = { x: 0, y: 0 };
  let imagePosition = { x: 0, y: 0 };
  let imageLoading = false;
  let fadeTransition = false;

  function openFullscreen(index) {
    fullscreenIndex = index;
    showFullscreen = true;
    scale = 1;
    scaleInput = "100";
    imagePosition = { x: 0, y: 0 };
  }

  function closeFullscreen() {
    showFullscreen = false;
    scale = 1;
    imagePosition = { x: 0, y: 0 };
  }

  function nextImage() {
    if (imageLoading) return;
    fadeTransition = true;
    setTimeout(() => {
      fullscreenIndex = (fullscreenIndex + 1) % images.length;
      scale = 1;
      scaleInput = "100";
      imagePosition = { x: 0, y: 0 };
      fadeTransition = false;
    }, 150);
  }

  function prevImage() {
    if (imageLoading) return;
    fadeTransition = true;
    setTimeout(() => {
      fullscreenIndex = (fullscreenIndex - 1 + images.length) % images.length;
      scale = 1;
      scaleInput = "100";
      imagePosition = { x: 0, y: 0 };
      fadeTransition = false;
    }, 150);
  }

  function zoomIn() {
    scale = Math.min(scale * 1.2, 3);
    scaleInput = Math.round(scale * 100).toString();
  }

  function zoomOut() {
    scale = Math.max(scale / 1.2, 0.5);
    if (scale === 1) {
      imagePosition = { x: 0, y: 0 };
    }
    scaleInput = Math.round(scale * 100).toString();
  }

  function resetZoom() {
    scale = 1;
    imagePosition = { x: 0, y: 0 };
    scaleInput = "100";
  }

  function toggleThumbnails() {
    showThumbnails = !showThumbnails;
  }

  function handleScaleInput(event) {
    const value = parseInt(event.target.value);
    if (!isNaN(value) && value >= 50 && value <= 300) {
      scale = value / 100;
      if (scale === 1) {
        imagePosition = { x: 0, y: 0 };
      }
    }
  }

  function handleScaleInputKeydown(event) {
    if (event.key === "Enter") {
      handleScaleInput(event);
      event.target.blur();
    }
  }

  function handleKeydown(event) {
    if (!showFullscreen) return;

    switch (event.key) {
      case "Escape":
        closeFullscreen();
        break;
      case "ArrowRight":
        nextImage();
        break;
      case "ArrowLeft":
        prevImage();
        break;
      case "=":
      case "+":
        zoomIn();
        break;
      case "-":
        zoomOut();
        break;
      case "0":
        resetZoom();
        break;
    }
  }

  function handleWheel(event) {
    event.preventDefault();
    if (event.deltaY < 0) {
      zoomIn();
    } else {
      zoomOut();
    }
  }

  function handleMouseDown(event) {
    if (scale > 1) {
      isDragging = true;
      dragStart = {
        x: event.clientX - imagePosition.x,
        y: event.clientY - imagePosition.y,
      };
    }
  }

  function handleMouseMove(event) {
    if (isDragging && scale > 1) {
      imagePosition = {
        x: event.clientX - dragStart.x,
        y: event.clientY - dragStart.y,
      };
    }
  }

  function handleMouseUp() {
    isDragging = false;
  }

  async function downloadImage(url, name) {
    try {
      let blob;
      
      // 检查是否为 base64 图片
      if (url.startsWith('data:')) {
        // 处理 base64 图片
        const response = await fetch(url);
        blob = await response.blob();
      } else {
        // 处理普通 URL 图片
        const response = await fetch(url);
        blob = await response.blob();
      }
      
      const downloadUrl = window.URL.createObjectURL(blob);
      
      const a = document.createElement("a");
      a.href = downloadUrl;
      a.download = name || 'image.jpg';
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      
      // 清理 URL 对象
      window.URL.revokeObjectURL(downloadUrl);
    } catch (error) {
      console.error('下载失败:', error);
      // 降级方案：对于 base64 图片直接下载
      if (url.startsWith('data:')) {
        const a = document.createElement("a");
        a.href = url;
        a.download = name || 'image.jpg';
        a.click();
      } else {
        // 对于普通 URL 使用原始方法
        const a = document.createElement("a");
        a.href = url;
        a.download = name || 'image.jpg';
        a.target = '_blank';
        a.click();
      }
    }
  }

  function close() {
    visible = false;
    dispatch("close");
  }

  // 自动打开全屏预览
  $: if (visible && images.length > 0) {
    openFullscreen(currentIndex);
  }

  // 当全屏关闭时，关闭整个组件
  $: if (!showFullscreen && visible) {
    close();
  }

  function handleImageLoad() {
    imageLoading = false;
  }

  function handleImageError() {
    imageLoading = false;
  }

  function switchToImage(index) {
    if (imageLoading || index === fullscreenIndex) return;
    fadeTransition = true;
    setTimeout(() => {
      fullscreenIndex = index;
      scale = 1;
      scaleInput = "100";
      imagePosition = { x: 0, y: 0 };
      fadeTransition = false;
    }, 150);
  }

  // 监听图片变化，设置加载状态
  $: if (images[fullscreenIndex]) {
    imageLoading = true;
  }
</script>

<svelte:window
  on:keydown={handleKeydown}
  on:mousemove={handleMouseMove}
  on:mouseup={handleMouseUp}
/>

{#if showFullscreen}
  <button class="fullscreen-overlay" on:click|self={closeFullscreen}>
    <div class="fullscreen-content">
      <div class="fullscreen-header">
        <div class="image-info">
          <span class="image-title"
            >{images[fullscreenIndex].name ||
              `图片 ${fullscreenIndex + 1}`}</span
          >
        </div>
        <div class="fullscreen-actions">
          <button
            class="download-btn"
            on:click={() =>
              downloadImage(
                images[fullscreenIndex].url,
                images[fullscreenIndex].name
              )}
            title="下载图片"
          >
            <svg
              width="16"
              height="16"
              viewBox="0 0 16 16"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M2 12.6673H14V14.0007H2V12.6673ZM8.66667 8.78172L12.7141 4.73432L13.6569 5.67713L8 11.334L2.34315 5.67713L3.28595 4.73432L7.33333 8.78172V1.33398H8.66667V8.78172Z"
                fill="white"
              />
            </svg>

            下载
          </button>
          <span class="image-counter"
            >{fullscreenIndex + 1} / {images.length}</span
          >

          <span class="action-line"></span>

          <button
            class="action-btn close-btn"
            on:click={closeFullscreen}
            title="关闭 (Esc)"
            ><svg
              width="24"
              height="24"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M17.7102 16.2902C17.8985 16.4785 18.0043 16.7339 18.0043 17.0002C18.0043 17.2665 17.8985 17.5219 17.7102 17.7102C17.5219 17.8985 17.2665 18.0043 17.0002 18.0043C16.7339 18.0043 16.4785 17.8985 16.2902 17.7102L12.0002 13.4102L7.71019 17.7102C7.52188 17.8985 7.26649 18.0043 7.00019 18.0043C6.73388 18.0043 6.47849 17.8985 6.29019 17.7102C6.10188 17.5219 5.99609 17.2665 5.99609 17.0002C5.99609 16.7339 6.10188 16.4785 6.29019 16.2902L10.5902 12.0002L6.29019 7.71019C6.10188 7.52188 5.99609 7.26649 5.99609 7.00019C5.99609 6.73388 6.10188 6.47849 6.29019 6.29019C6.47849 6.10188 6.73388 5.99609 7.00019 5.99609C7.26649 5.99609 7.52188 6.10188 7.71019 6.29019L12.0002 10.5902L16.2902 6.29019C16.4785 6.10188 16.7339 5.99609 17.0002 5.99609C17.2665 5.99609 17.5219 6.10188 17.7102 6.29019C17.8985 6.47849 18.0043 6.73388 18.0043 7.00019C18.0043 7.26649 17.8985 7.52188 17.7102 7.71019L13.4102 12.0002L17.7102 16.2902Z"
                fill="white"
              />
            </svg>
          </button>
        </div>
      </div>

      <div class="fullscreen-image-container" on:wheel={handleWheel}>
        {#if images.length > 1}
          <button
            class="nav-btn prev"
            on:click={prevImage}
            disabled={imageLoading}>❮</button
          >
        {/if}

        <div class="image-wrapper">
          {#if imageLoading}
            <div class="loading-container">
              <div class="loading-spinner"></div>
            </div>
          {/if}

          <img
            src={images[fullscreenIndex].url}
            alt={images[fullscreenIndex].name}
            class="fullscreen-image"
            class:draggable={scale > 1}
            class:fade-out={fadeTransition}
            class:loading={imageLoading}
            style="transform: scale({scale}) translate({imagePosition.x /
              scale}px, {imagePosition.y / scale}px); cursor: {scale > 1
              ? isDragging
                ? 'grabbing'
                : 'grab'
              : 'default'}"
            on:mousedown={handleMouseDown}
            on:dragstart|preventDefault
            on:load={handleImageLoad}
            on:error={handleImageError}
          />
        </div>

        {#if images.length > 1}
          <button
            class="nav-btn next"
            on:click={nextImage}
            disabled={imageLoading}>❯</button
          >
        {/if}
      </div>

      {#if images.length > 1 && showThumbnails}
        <div class="thumbnail-strip">
          {#each images as image, index}
            <img
              src={image.url}
              alt={image.name}
              class="thumbnail"
              class:active={index === fullscreenIndex}
              class:loading-thumb={imageLoading && index === fullscreenIndex}
              on:click={() => switchToImage(index)}
            />
          {/each}
        </div>
      {/if}
    </div>
  </button>
{/if}

<style>
  .fullscreen-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    flex-direction: column;
    z-index: 1001;
  }

  .fullscreen-content {
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .fullscreen-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1.25rem;
    color: white;
  }

  .image-info {
    display: flex;
    align-items: center;
    gap: 1rem;
  }

  .image-counter {
    margin-right: 8px;
    font-size: 14px;
   }

  .image-title {
    font-weight: 500;
    font-size: 16px;
  }

  .fullscreen-actions {
    display: flex;
    gap: 16px;
    align-items: center;
  }

  .scale-input-container {
    position: relative;
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 4px;
    padding: 2px 8px;
    min-width: 60px;
  }

  .scale-input {
    background: transparent;
    border: none;
    color: #374151;
    font-size: 0.9rem;
    width: 40px;
    padding: 4px 2px;
    text-align: center;
    outline: none;
  }

  .scale-input:focus {
    background: rgba(59, 130, 246, 0.1);
  }

  .scale-unit {
    color: #6b7280;
    font-size: 0.8rem;
    margin-left: 2px;
  }

  .action-line{
    width: 1px;
    height: 18px;
    background: #595959;

  
    align-self: center;
  }
  .action-btn {
    background: rgba(255, 255, 255, 0.9);
    border: none;
    border-radius: 4px;
    padding: 6px 10px;
    cursor: pointer;
    font-size: 0.9rem;
    transition: all 0.2s;
    min-width: 32px;
  }

  .action-btn:hover:not(:disabled) {
     transform: scale(1.1);
  }

  .action-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .fullscreen-image-container {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
  }

  .image-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
  }

  .loading-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 1rem;
    color: white;
    z-index: 5;
  }

  .loading-spinner {
    width: 30px;
    height: 30px;
    border: 3px solid rgba(255, 255, 255, 0.3);
    border-top: 3px solid white;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  .loading-text {
    font-size: 0.9rem;
    opacity: 0.8;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }

  .fullscreen-image {
    max-width: 90%;
    max-height: 90%;
    object-fit: contain;
    transition:
      transform 0.2s ease-out,
      opacity 0.3s ease-in-out;
    user-select: none;
    opacity: 1;
  }

  .fullscreen-image.loading {
    opacity: 0;
  }

  .fullscreen-image.fade-out {
    opacity: 0;
  }

  .fullscreen-image.draggable {
    transition: opacity 0.3s ease-in-out;
  }

  .nav-btn {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background: rgba(38, 38, 38, 0.9);
    color: white;

     border: none;
    border-radius: 50%;
    width: 48px;
    height: 48px;
    font-size: 1.2rem;
    cursor: pointer;
    transition: all 0.2s;
    z-index: 10;
  }

  .nav-btn:hover:not(:disabled) {
     transform: translateY(-50%) scale(1.1);
  }

  .nav-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  .nav-btn.prev {
    left: 20px;
  }

  .nav-btn.next {
    right: 20px;
  }

  .thumbnail-strip {
    display: flex;
    justify-content: center;
    gap: 8px;
    padding: 1rem;
    background: rgba(0, 0, 0, 0.5);
    overflow-x: auto;
  }

  .thumbnail {
    width: 60px;
    height: 45px;
    object-fit: cover;
    border-radius: 4px;
    cursor: pointer;
    opacity: 0.6;
    transition: all 0.2s;
    border: 2px solid transparent;
  }

  .thumbnail:hover {
    opacity: 0.8;
  }

  .thumbnail.active {
    opacity: 1;
    border-color: #3b82f6;
  }

  .thumbnail.loading-thumb {
    opacity: 0.3;
    cursor: not-allowed;
  }

  .download-btn {
    border: none;
    border-radius: 6px;
    padding: 8px 12px;
    cursor: pointer;
    font-size: 0.85rem;
    font-weight: 500;
    background-color: transparent;
    color: #fff;
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .download-btn svg {
    flex-shrink: 0;
  }

  .close-btn {
    color: white;
    font-weight: bold;
    background: transparent;
  }
  .close-btn:hover {
    background: transparent;
  }

  @media (max-width: 768px) {
    .nav-btn {
      width: 40px;
      height: 40px;
      font-size: 1rem;
    }

    .nav-btn.prev {
      left: 10px;
    }

    .nav-btn.next {
      right: 10px;
    }

    .thumbnail {
      width: 50px;
      height: 37px;
    }

    .fullscreen-actions {
      gap: 4px;
      flex-wrap: wrap;
    }

    .scale-input-container {
      min-width: 50px;
      padding: 1px 6px;
    }

    .scale-input {
      width: 35px;
      font-size: 0.8rem;
      padding: 2px 1px;
    }

    .scale-unit {
      font-size: 0.7rem;
    }

    .loading-spinner {
      width: 32px;
      height: 32px;
    }

    .loading-text {
      font-size: 0.8rem;
    }

    .download-btn {
      padding: 6px 10px;
      font-size: 0.8rem;
      gap: 4px;
    }

    .download-btn svg {
      width: 14px;
      height: 14px;
    }
  }
</style>
